package software;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import javax.swing.*;


public class Menu extends JFrame {
	private static final long serialVersionUID = 1L;
	//菜单部分
	private static final String[] MENU_0 = {"/srcImages/Menu_0.jpg","批量产生习题","随机产生习题",
		"近期练习报告","批量批改操练","联机操练习题","退出程序"};
	private static final String[] MENU_0_0 = {"/srcImages/Menu_0_0.jpg","返回上层"};
	private static final String[] MENU_0_1 = {"/srcImages/Menu_0_0.jpg","返回上层"};
	private static final String[] MENU_0_2 = {"/srcImages/Menu_0_0.jpg","返回上层"};
	private static final String[] MENU_0_3 = {"/srcImages/Menu_0_0.jpg","返回上层"};
	private static final String[] MENU_0_4 = {"/srcImages/Menu_0_0.jpg","返回上层"};
	private static final String Main_Title = "100以内口算练习";
	private String buttonBg = "/srcImages/button.png";
	private String buttonBg2 = "/srcImages/button2.png";
	private String boardBg = "/srcImages/boardBg.png";
	private String Tab = "|..";
	
	//各个文件夹
	private File ExercisesDir = null;
	private File ExercisesAdditionsDir = null;
	private File ExercisesSubstractsDir = null;
	private File ExercisesOperationsDir = null;
	private File PracticesDir = null;
	private File PracticesCorrected = null;//批改后的习题文件和答案文件
	private File PracticesCheckings = null;//批改结果文档
	private File PracticesRecord = null;//记录文档
	private File recordFile = null;//记录文件
	//常用变量的初始化
	private OperationBase base = new OperationBase();
	private Judegement Judge = new Judegement();
	//操练时临时引用文件
	private Exercise exercise = null;
	private String filename = null;
	private File practicefile = null;
	
	private static final int Width = 1050;//窗口初始宽度
	private static final int Heigth = 720;//窗口初始高度
	private static final int BoardWidth = 750;//黑板宽度
	private static final int BoardHeigth = 576;//黑板高度

	private static Stopwatch stopwatch = new Stopwatch();

	private long elapsedTime = 0;

	Thread thread = new Thread(new Runnable() {
		public void run() {
			while (true) {
				elapsedTime = stopwatch.getElapsedTime();
				// 程序逻辑代码
				stopwatch.start();
				System.out.println(elapsedTime);
			}
		}
	});

	//组件
	private Image icon = new ImageIcon(getClass().
			getResource("/srcImages/HHXY.png")).getImage();//窗口图标
	private JButton button[] = new JButton[7];
	private JPanel panel;
	private BoardPanel board;
	private JScrollPane boardjsp;//黑板的滑动窗口
	private Image image;
	private Font f = new Font("黑体",Font.BOLD,20);//常用字体类型

	private Font r = new Font("黑体",Font.BOLD,20);

	//构造函数，提前生成文件夹
	public Menu() {
		ExercisesDir = new File("Exercises");
		if(!ExercisesDir.isDirectory()) {
			ExercisesDir.mkdir();
		}
		PracticesDir = new File("Practices");
		if(!PracticesDir.isDirectory()) {
			PracticesDir.mkdir();
		}
		ExercisesAdditionsDir = new File("Exercises/Additions");
		if(!ExercisesAdditionsDir.isDirectory()) {
			ExercisesAdditionsDir.mkdirs();
		}
		ExercisesSubstractsDir = new File("Exercises/Substracts");
		if(!ExercisesSubstractsDir.isDirectory()) {
			ExercisesSubstractsDir.mkdirs();
		}
		ExercisesOperationsDir = new File("Exercises/Operations");
		if(!ExercisesOperationsDir.isDirectory()) {
			ExercisesOperationsDir.mkdirs();
		}
		PracticesCorrected = new File("Practices/Corrected");
		if(!PracticesCorrected.isDirectory()) {
			PracticesCorrected.mkdirs();
		}
		PracticesCheckings = new File("Practices/Checkings");
		if(!PracticesCheckings.isDirectory()) {
			PracticesCheckings.mkdirs();
		}
		PracticesRecord = new File("Practices/Record");
		if(!PracticesRecord.isDirectory()) {
			PracticesRecord.mkdirs();
		}
		recordFile = new File(PracticesRecord,"record.csv");
		try {
			if(!recordFile.exists()) {
				recordFile.createNewFile();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		//窗口设置
		this.setTitle(Main_Title);//标题
		this.setBounds(0, 0,Width, Heigth);//设置窗口长宽
		this.setResizable(false);//是否可以改变窗口大小
		this.setIconImage(icon);//设置窗口图标
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//点击关闭按钮不做处理
		this.addWindowListener(new WindowAdapter() {//添加退出询问
			public void windowClosing(WindowEvent e) {
				doExit();
			}
		});
		this.setLayout(null);//设置布局方式
		this.setLocation(200, 80);//设置窗口初始位置
		this.setVisible(true);
	}
	//退出的函数
	private void doExit() {
		int n = JOptionPane.showConfirmDialog(null,"",
				"你学习了"+stopwatch.parseTotime(elapsedTime),JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE
				,new ImageIcon(getClass().getResource("/srcImages/exitwaring.jpg")));

		
		//取消选择是-1,确定是0,取消是1
		if(n==0) {
			System.exit(0);//那么退出
		}
	}
	
	//画菜单方法复用
	private void Menu_0__(String[] str,String Title) {
		this.getContentPane().removeAll();//清空frame
		this.repaint();//重新绘制
		this.setTitle(Main_Title+Title);
		//添加背景图片
		image = new ImageIcon(getClass().getResource(str[0])).getImage();
		panel = new BackgroundPanel(image);
		panel.setBounds(0, 0, Width, Heigth);
		panel.setLayout(null);
		for(int i=1;i<str.length;++i) {
			button[i-1] = new MyButton(buttonBg,Width/2-500, i*Heigth/10-20, 200, 50,str[i]);
			panel.add(button[i-1]);
		}
		this.add(panel);
		this.setVisible(true);
		panel.updateUI();
	}
	
	//主菜单运行函数
	public void Menu_0_UI() {
		Menu_0__(MENU_0,"程序");
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_0_UI();
		});
		button[1].addActionListener((ActionEvent e)->{
			Menu_0_1_UI();
		});
		button[2].addActionListener((ActionEvent e)->{
			Menu_0_2_UI();
		});
		button[3].addActionListener((ActionEvent e)->{
			Menu_0_3_UI();
		});
		button[4].addActionListener((ActionEvent e)->{
			Menu_0_4_UI();
		});
		button[5].addActionListener((ActionEvent e)->{
			doExit();//调用退出时方法
		});
	}
	
	//请用户选择，并返回选择，不合法返回-1
	private int MakeChoiceInt(int upper,JTextArea text,String warn) {
		String Case;
		int res;
		Case = text.getText().trim();
		if(Case.matches("[0-9]{1,4}")) {
			res = Integer.parseInt(Case);
			if(res<=upper&res>0)return res;
		}
		JOptionPane.showMessageDialog(null, warn+"请输入1到"+upper+"的数字",
				"温馨提示",JOptionPane.INFORMATION_MESSAGE);
		return -1;
	}
	
	//生成加法习题函数
	private String CreateAdditionExercises(int cnt1,int cnt2) {
		Exercise anExercise = null;
		String res = Tab+"生成的加法习题文件:<br><br>";
		int cnt=0,i=0;
		while(cnt<cnt1){
			++i;
			File temp = new File(ExercisesAdditionsDir.getAbsolutePath(),
					"addition_exercise_count_"+cnt2+"_"+i+".csv");
			if(FindAllFile(ExercisesDir,temp)!=null) {
				continue;
			}
			anExercise = base.generateAdditionExercise(cnt2);
			anExercise.writeCSVAddtionExercise(cnt2,temp);
			res = res + Tab+temp.getName() + "<br><br>";
			cnt++;
		}
		res = res + Tab+"已经将"+cnt1+"套"+cnt2+"个算式的加法习题写入:"+"<br>"+Tab+
				ExercisesAdditionsDir.getAbsolutePath()+"文件夹<br><br>";
		return res;
	}
	//生成减法习题函数
	private String CreateSubtractExercises(int cnt1,int cnt2) {
		Exercise anExercise = null;
		String res = Tab+"生成的减法习题文件:<br><br>";
		int cnt=0,i=0;
		while(cnt<cnt1){
			++i;
			File temp = new File(ExercisesSubstractsDir.getAbsolutePath(),
					"substract_exercise_count_"+cnt2+"_"+i+".csv");
			if(FindAllFile(ExercisesDir,temp)!=null) {
				continue;
			}
			anExercise = base.generateSubtractExercise(cnt2);
			anExercise.writeCSVSubstractExercise(cnt2,temp);
			res = res + Tab+temp.getName() + "<br><br>";
			cnt++;
		}
		res = res + Tab+"已经将"+cnt1+"套"+cnt2+"个算式的减法习题写入:"+"<br>"+Tab+
				ExercisesSubstractsDir.getAbsolutePath()+"文件夹"+"<br><br>";
		return res;
	}
	//生成混合习题函数
	private String CreateBinaryExercises(int cnt1,int cnt2) {
		Exercise anExercise = null;
		String res = Tab+"生成的混合习题文件:<br><br>";
		int cnt=0,i=0;
		while(cnt<cnt1){
			++i;
			File temp = new File(ExercisesOperationsDir.getAbsolutePath(),
					"binary_exercise_count_"+cnt2+"_"+i+".csv");
			if(FindAllFile(ExercisesDir,temp)!=null) {
				continue;
			}
			anExercise = base.generateExercise(cnt2);
			anExercise.writeCSVBinaryExercise(cnt2,temp);
			res = res + Tab+temp.getName() + "<br><br>";
			cnt++;
		}
		res = res + Tab+"已经将"+cnt1+"套"+cnt2+"个算式的混合习题写入:"+"<br>"+Tab+
				ExercisesOperationsDir.getAbsolutePath()+"文件夹<br><br>";
		return res;
	}
	
	//批量产生习题菜单
	private void Menu_0_0_UI() {
		Menu_0__(MENU_0_0,"-批量产生习题");
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_UI();
		});
		
		JLabel label1 = new JLabel("习题类型：");    //创建标签
		JLabel label2 = new JLabel("习题套数：");    //创建标签
		JLabel label3 = new JLabel("每套的算式数量：");    //创建标签
		JLabel label4 = new JLabel("注意:数量都不要超过200");    //创建标签
		JLabel label5 = new JLabel();//用来程序输出信息

		//设置字体大小类型
		label1.setFont(f);
		label2.setFont(f);
		label3.setFont(f);
		label4.setFont(f);
		label5.setFont(f);
		label4.setForeground(Color.red);
        JComboBox<String> cmb = new JComboBox<String>();    //创建JComboBox
        //向下拉列表中添加项
        cmb.addItem("加法习题");
        cmb.addItem("减法习题");
        cmb.addItem("混合习题");
        cmb.setFont(f);
        JTextArea text1 = new JTextArea();
        text1.setFont(f);
        JTextArea text2 = new JTextArea();
        text2.setFont(f);
        //设置各个组件的大小位置
        label1.setBounds(Width/2-500, 6*Heigth/20-20, 200, 25);
        cmb.setBounds(Width/2-500, 7*Heigth/20-20, 200, 25);
        label2.setBounds(Width/2-500, 8*Heigth/20-20, 200, 25);
        text1.setBounds(Width/2-500, 9*Heigth/20-20, 200, 25);
        label3.setBounds(Width/2-500, 10*Heigth/20-20, 200, 25);
        text2.setBounds(Width/2-500, 11*Heigth/20-20, 200, 25);
        label4.setBounds(Width/2-500, 12*Heigth/20-20, 250, 25);
        label5.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
		label5.setBounds(Width/2-200, Heigth/10, 650, 8*Heigth/10);
        label5.setOpaque(true);//设置可见
        label5.setBackground(Color.white);
        //为label5添加滑块
        JScrollPane jsp = new JScrollPane(label5);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
        
        panel.add(label1);
        panel.add(cmb);
        panel.add(label2);
        panel.add(text1);
        panel.add(label3);
        panel.add(text2);
        panel.add(label4);
        panel.add(jsp);

        button[1] = new MyButton(buttonBg2,Width/2-500, 14*Heigth/20-20, 200, 50,"生成习题");
		button[1].addActionListener((ActionEvent e)->{
			int cnt1 = 0,cnt2 = 0;
			cnt1 = MakeChoiceInt(200,text1,"习题套数");
			if(cnt1 == -1) {
				return;
			}
			cnt2 = MakeChoiceInt(200,text2,"每套算式数量");
			if(cnt2 == -1)return;
			String Case = cmb.getSelectedItem().toString();
			String res = "";
			switch(Case){
				case "加法习题":res = CreateAdditionExercises(cnt1,cnt2);break;
				case "减法习题":res = CreateSubtractExercises(cnt1,cnt2);break;
				case "混合习题":res = CreateBinaryExercises(cnt1,cnt2);break;
			}
			label5.setText("<html><body>"+res+Tab+"运行完毕"+"<body></html>");
		});
		panel.add(button[1]);
		panel.add(button[6]);
	}
	//随机产生习题菜单
	private void Menu_0_1_UI() {
		Menu_0__(MENU_0_1,"-随机产生习题");
		//返回上层的实现
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_UI();
		});
		

		JLabel label4 = new JLabel("<html><body>"+"提示：随机产生习题是加法、减法和混合习题分别随机产生几套数量"
				+ "随机的习题集，并存入到文件中"+"<body></html>");    //创建标签
		JLabel label5 = new JLabel();//用来程序输出信息
		label4.setFont(f);
		label5.setFont(f);
        
        label4.setBounds(Width/2-500, 10*Heigth/20-20, 250, 100);
        label5.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
        label5.setOpaque(true);//设置label5可见
        label5.setBackground(Color.white);
        //为label5添加滑块
        JScrollPane jsp = new JScrollPane(label5);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
        
        panel.add(label4);
        panel.add(jsp);
        //开始随机产生的实现
        button[1] = new MyButton(buttonBg2,Width/2-500, 14*Heigth/20-20, 200, 50,"生成习题");
		button[1].addActionListener((ActionEvent e)->{
			Random r = new Random();
			
			String res = "";
			int cnt1 = r.nextInt(10)+1;
			int cnt2 = (r.nextInt(10)+1)*10;
			res = res + CreateAdditionExercises(cnt1,cnt2);
			cnt1 = r.nextInt(10)+1;
			cnt2 = (r.nextInt(10)+1)*10;
			res = res + CreateSubtractExercises(cnt1,cnt2);
			cnt1 = r.nextInt(10)+1;
			cnt2 = (r.nextInt(10)+1)*10;
			res = res + CreateBinaryExercises(cnt1,cnt2);

			label5.setText("<html><body>"+res+Tab+"运行完毕"+"<body></html>");
		});
		panel.add(button[1]);
		panel.add(button[6]);
	}

	//在文件夹dir中找obfile(子文件也找),找到了返回文件,没有返回空
	private File FindAllFile(File dir,File obfile) {
		File[] listOfFiles = dir.listFiles();
		for(File file : listOfFiles) {
			if(file.isFile()&&file.getName().equals(obfile.getName())) {
				return file;
			}else if(file.isDirectory()){
				if(FindAllFile(file,obfile)!=null)
					return FindAllFile(file,obfile);
			}
		}
		return null;
	}
	//查找dir是否存在obfile文件(不深层查找)，存在返回该文件，不存在返回null
	private File FindFile(File dir,File obfile) {
		File[] listOfFiles = dir.listFiles();
		for(File file : listOfFiles) {
			if(file.isFile()&&file.getName().equals(obfile.getName())) {
				return file;
			}
		}
		return null;
	}
	//移动文件函数
	private void moveFile(File file,File Dir,boolean display) {
		if(display)System.out.println("文件"+file.getName()+"由:"+file.getParentFile().getAbsolutePath()+
				"\n\t移动至:"+Dir.getAbsolutePath());
		file.renameTo(new File(Dir,file.getName()));
	}

	//查看最近状态菜单
	private void Menu_0_2_UI() {
		Menu_0__(MENU_0_2,"-查看最近状态");
		//返回上层按钮的实现
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_UI();
		});
		DataPanel board = new DataPanel(new ImageIcon(getClass().getResource(boardBg)).getImage(),recordFile);
        //为borad添加滑块
        boardjsp = new JScrollPane(board);
        boardjsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        boardjsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        boardjsp.setBorder(null);//设置没有边框
        board.setBounds(Width/2-280, Heigth/10-20, BoardWidth, BoardHeigth);
        boardjsp.setBounds(Width/2-280, Heigth/10-20, BoardWidth, BoardHeigth);
        board.flush();
        panel.add(boardjsp);
	}
	
	//批量批改习题菜单
	private void Menu_0_3_UI() {
		Menu_0__(MENU_0_3,"-批量批改习题");
		//返回按钮的实现
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_UI();
		});
		
		
		JLabel label4 = new JLabel("<html><body>"+"提示：批量批改是将待批改文件夹"+
				"中所有做好的习题批改(自行添加的文件的格式要求,请看说明书)"+"<body></html>");    //创建标签
		JLabel label5 = new JLabel();//用来程序输出信息
		label4.setFont(f);
		label5.setFont(f);
        
        label4.setBounds(Width/2-500, 10*Heigth/20-20, 250, 100);
        label5.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
        label5.setOpaque(true);
        label5.setBackground(Color.white);
        //为输出信息的窗口label5设置滑块
        JScrollPane jsp = new JScrollPane(label5);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setBounds(Width/2-200, Heigth/10-20, 650, 8*Heigth/10);
        
        panel.add(label4);
        panel.add(jsp);
        //开始批改的实现
        button[1] = new MyButton(buttonBg2,Width/2-500, 14*Heigth/20-20, 200, 50,"开始批改");
		button[1].addActionListener((ActionEvent e)->{
			File[] listOfFiles = PracticesDir.listFiles();
			String res = Tab+"批改的习题文件:<br><br>";
			int cnt = 0;
			for(File file1 : listOfFiles) {
				if(file1.isFile() && file1.getName().endsWith(".csv")
						&& !file1.getName().startsWith("results_")) {
					File file2 = FindFile(PracticesDir,new File("results_"+file1.getName()));
					if(file2.exists()) {
						File file3 = new File(PracticesCheckings,"checking_"+file1.getName());
						Judge.Judege(file2, file1, file3);
						moveFile(file1,PracticesCorrected,true);
						moveFile(file2,PracticesCorrected,true);
						res = res + Tab + file1.getName() + "<br><br>";
						cnt++;
					}
				}
			}
			res = res + Tab + "批量批改完毕,批改后的"+cnt+"个习题文件存入了:<br>"+Tab
					+PracticesCorrected.getAbsolutePath()+" <br>";
			res = res + Tab + "批改后的批改结果文件存入了:<br>"+Tab
					+PracticesCheckings.getAbsolutePath()+" <br><br>";
			label5.setText("<html><body>"+res+Tab+"运行完毕"+"<body></html>");
		});
		panel.add(button[1]);
		panel.add(button[6]);
	}
	//联机操练习题的菜单运行函数
	private void Menu_0_4_UI(){
		Menu_0__(MENU_0_4,"-联机操练习题");
		button[0].addActionListener((ActionEvent e)->{
			Menu_0_UI();
		});

		
		JLabel label1 = new JLabel("习题类型：");    //创建标签
		label1.setFont(f);
		JComboBox<String> cmb = new JComboBox<String>();    //创建JComboBox
        //向下拉列表中添加项
        cmb.addItem("不限");
        cmb.addItem("加法习题");
        cmb.addItem("减法习题");
        cmb.addItem("混合习题");
        cmb.setFont(f);
		
		JLabel label2 = new JLabel("算式数量：");
		label2.setFont(f);
		JComboBox<String> cmb2 = new JComboBox<String>();    //创建JComboBox
        //向下拉列表中添加项
        cmb2.addItem("不限");
        cmb2.addItem("5");
        cmb2.addItem("10");
        cmb2.addItem("20");
        cmb2.addItem("40");
        cmb2.addItem("50");
        cmb2.addItem("80");
        cmb2.addItem("100");
        cmb2.setFont(f);
		
		board = new BoardPanel(new ImageIcon(getClass().getResource(boardBg)).getImage());
        //为borad添加滑块
        boardjsp = new JScrollPane(board);
        boardjsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        boardjsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        boardjsp.setBorder(null);//设置没有边框

        JLabel label3 = new JLabel("选择习题文件:");
        label3.setFont(f);
        //习题文件的下拉列表
        JComboBox<String> cmb3 = new JComboBox<String>();    //创建JComboBox
        //向下拉列表中添加项
        cmb3.setFont(f);
        //初始化cmb3
        File[] files1 = ExercisesAdditionsDir.listFiles();
    	File[] files2 = ExercisesSubstractsDir.listFiles();
    	File[] files3 = ExercisesOperationsDir.listFiles();
    	if(files1.length==0&&files2.length==0&&files3.length==0) {
    		cmb3.addItem("没有想要的习题文件呢，先去生成吧");
    	}else {
    		for(File file:files1) cmb3.addItem(file.getName());
			for(File file:files2) cmb3.addItem(file.getName());
    		for(File file:files3) cmb3.addItem(file.getName());
    	}

		//创建预览按钮
        button[1] = new JButton("预览");
        button[1].setFont(f);

		//为预览按钮添加监听器
		button[1].addActionListener((ActionEvent e)->{
			filename = cmb3.getSelectedItem().toString();
			if(filename.startsWith("没"))return;
			practicefile = new File(filename);
			practicefile = FindAllFile(ExercisesDir,practicefile);
			if(practicefile==null) {
				JOptionPane.showMessageDialog(null,"文件不存在!",
						"温馨提示",JOptionPane.INFORMATION_MESSAGE);
			}else {
				exercise = new Exercise().readCSVBinaryExercise(practicefile);
				board.setExercise(exercise);
				board.DrawExercise();
				board.DrawResultText();//画文本框，但是暂时还不可编辑
			}
		});


		//创建选择文件按钮
		button[6] = new JButton("选择文件");
		button[6].setFont(f);


        

        //给类型下拉列表添加监听器，改变选项就改变可选习题的下拉列表，(改类型)
        cmb.addActionListener((ActionEvent e)->{
        	cmb3.removeAllItems();
			switch(cmb.getSelectedItem().toString()) {
				case "不限":
					for(File file:files1) cmb3.addItem(file.getName());
					for(File file:files2) cmb3.addItem(file.getName());
		    		for(File file:files3) cmb3.addItem(file.getName());
					break;
				case "加法习题":
					for(File file:files1) cmb3.addItem(file.getName());
					break;
				case "减法习题":
					for(File file:files2) cmb3.addItem(file.getName());
					break;
				case "混合习题":
					for(File file:files3) cmb3.addItem(file.getName());
					break;
			}
			if(cmb3.getItemCount() == 0) {
				cmb3.addItem("没有想要的习题文件呢，先去生成吧");
			}
		});
        
        //给数量下拉列表添加监听器，改变选项就改变可选习题的下拉列表，(改数量)
        cmb2.addActionListener((ActionEvent e)->{
        	cmb3.removeAllItems();
			switch(cmb.getSelectedItem().toString()) {
				case "不限":
					for(File file:files1) cmb3.addItem(file.getName());
					for(File file:files2) cmb3.addItem(file.getName());
		    		for(File file:files3) cmb3.addItem(file.getName());
					break;
				case "加法习题":
					for(File file:files1) cmb3.addItem(file.getName());
					break;
				case "减法习题":
					for(File file:files2) cmb3.addItem(file.getName());
					break;
				case "混合习题":
					for(File file:files3) cmb3.addItem(file.getName());
					break;
			}
			if(cmb3.getItemCount() == 0) {
				cmb3.addItem("没有想要的习题文件呢，先去生成吧");
			}
        	if(cmb3.getSelectedItem().toString().startsWith("没")|
        			cmb2.getSelectedIndex()==0) {
        		return;
        	}
        	int i=0;
        	while(i<cmb3.getItemCount()) {
        		if(!cmb3.getItemAt(i).toString().matches("[a-z_]*"+
        				cmb2.getSelectedItem().toString()+"[_][0-9]*[\\.]csv")) {
        			cmb3.removeItemAt(i);
        		}else ++i;
        	}
        	if(cmb3.getItemCount()==0) {
        		cmb3.addItem("没有想要的习题文件呢，先去生成吧");
        	}
        });
        //开始操练按钮
        button[2] = new MyButton(buttonBg2,Width/2-500, 14*Heigth/20-20, 200, 50,"开始操练");
        //为开始操练按钮添加监听器
        button[2].addActionListener((ActionEvent e)->{

			thread.start();

        	//这部分与预览按钮一样
        	filename = cmb3.getSelectedItem().toString();
        	if(filename.startsWith("没"))return;
        	practicefile = new File(filename);
    		practicefile = FindAllFile(ExercisesDir,practicefile);
    		if(practicefile==null) {
    			JOptionPane.showMessageDialog(null,"文件不存在!",
    					"温馨提示",JOptionPane.INFORMATION_MESSAGE);
    		}else {
    			exercise = new Exercise().readCSVBinaryExercise(practicefile);
    			board.setExercise(exercise);
    			board.DrawExercise();
    			board.DrawResultText();//画文本框，但是暂时还不可编辑
    		}
    		//绘制操练界面
        	DrawPractice();
        });
        
        //设置各个部件大小
        button[1].setBounds(Width/2+320, Heigth/10-57, 80, 25);
		button[6].setBounds(Width/2+400, Heigth/10-57, 80, 25);
        label1.setBounds(Width/2-500, 5*Heigth/20-20, 200, 25);
        cmb.setBounds(Width/2-500, 6*Heigth/20-20, 200, 25);
        label2.setBounds(Width/2-500, 7*Heigth/20-20, 200, 25);
        cmb2.setBounds(Width/2-500, 8*Heigth/20-20, 200, 25);
        board.setBounds(Width/2-280, Heigth/10-20, BoardWidth, BoardHeigth);
        board.setLayout(null);//设置布局方式
        boardjsp.setBounds(Width/2-280, Heigth/10-20, BoardWidth, BoardHeigth);
        label3.setBounds(Width/2-250, Heigth/10-55, 200, 25);
        cmb3.setBounds(Width/2-100, Heigth/10-57, 400, 25);
        
        //将各个组件添加进panel
        panel.add(label3);
        panel.add(cmb3);
        panel.add(button[1]);
        panel.add(label1);
        panel.add(cmb);
        panel.add(label2);
        panel.add(cmb2);
        panel.add(boardjsp);
        panel.add(button[2]);
	}
	//操练习题的界面，包含展示习题，操练习题，批改
	private void DrawPractice() {
		panel.removeAll();//清空
		panel.repaint();//重新绘制
		
		panel.add(boardjsp);//把之前预览的黑板画上
		board.setResEditable();//设置文本可编辑
//		board.DrawAnsLabels();//画答案
		
		JLabel label1 = new JLabel("正在操练的习题文件:");
        label1.setFont(f);
		label1.setBounds(Width/2-250, Heigth/10-55, 200, 25);
		JLabel label2 = new JLabel(filename);//提示正在操练的习题
		label2.setFont(f);//设置字体
		label2.setBorder(BorderFactory.createLineBorder(Color.darkGray, 1));//设置边框
		label2.setHorizontalAlignment(JLabel.CENTER);//字体居中
        label2.setBounds(Width/2-20, Heigth/10-57, 400, 25);
        panel.add(label1);
        panel.add(label2);


        
        //返回上层按钮
        button[1] = new MyButton(buttonBg,Width/2-500, 2*Heigth/20-20, 200, 50,"回退");
        //添加监听器
        button[1].addActionListener((ActionEvent e)->{
        	Menu_0_4_UI();
			stopwatch.stop();
        });
        button[1].setEnabled(false);//开始不可按，提交后才可
        panel.add(button[1]);


        
        //加上一些提示，对用户友好.
        //提示题目类型
        JLabel label3 = new JLabel("题目类型:");
        label3.setFont(f);
        label3.setBounds(Width/2-500, 5*Heigth/20-20, 100, 25);
        panel.add(label3);
        JTextArea text3 = new JTextArea();
        text3.setFont(f);
        text3.setEditable(false);//设置不可编辑
        String str1 = "仅加法";
        if(filename.startsWith("s"))str1="仅减法";
        else if(filename.startsWith("b"))str1="加减混合";
        text3.setText(str1);
        text3.setBounds(Width/2-400, 5*Heigth/20-20, 100, 25);
        panel.add(text3);
        //提示算式数量
        JLabel label4 = new JLabel("题目数量:");
        label4.setFont(f);
        label4.setBounds(Width/2-500, 6*Heigth/20-20, 100, 25);
        panel.add(label4);
        JTextArea text4 = new JTextArea();
        text4.setFont(f);
        text4.setEditable(false);//设置不可编辑
        text4.setText(String.valueOf(board.getExercisesCount()));
        text4.setBounds(Width/2-400, 6*Heigth/20-20, 100, 25);
        panel.add(text4);
        //告知统计结果
        //正确题数
        JLabel label5 = new JLabel("正确题数:");
        label5.setFont(f);
        label5.setBounds(Width/2-500, 8*Heigth/20-20, 100, 25);
        panel.add(label5);

		JLabel labelTimer = new JLabel("答题计时:");
		labelTimer.setBounds(Width/2-500, 11*Heigth/20-20, 100, 25);
		labelTimer.setFont(r);
		labelTimer.setForeground(Color.RED);
		panel.add(labelTimer);
		JTextArea textTimer = new JTextArea();
		textTimer.setFont(f);
		textTimer.setEditable(false);//设置不可编辑
		textTimer.setText("提交后可见");
		textTimer.setForeground(Color.gray);
		textTimer.setBounds(Width/2-400, 11*Heigth/20-20, 105, 25);
		panel.add(textTimer);



        JTextArea text5 = new JTextArea();
        text5.setFont(f);
        text5.setEditable(false);//设置不可编辑
        text5.setText("提交后可见");
        text5.setForeground(Color.gray);
        text5.setBounds(Width/2-400, 8*Heigth/20-20, 105, 25);
        panel.add(text5);
        //错误题数
        JLabel label6 = new JLabel("错误题数:");
        label6.setFont(f);
        label6.setBounds(Width/2-500, 9*Heigth/20-20, 100, 25);
        panel.add(label6);
        JTextArea text6 = new JTextArea();
        text6.setFont(f);
        text6.setEditable(false);//设置不可编辑
        text6.setText("提交后可见");
        text6.setForeground(Color.gray);
        text6.setBounds(Width/2-400, 9*Heigth/20-20, 105, 25);
        panel.add(text6);
        //正确率
        JLabel label7 = new JLabel("正确率:");
        label7.setFont(f);
        label7.setBounds(Width/2-500, 10*Heigth/20-20, 100, 25);
        panel.add(label7);
        JTextArea text7 = new JTextArea();
        text7.setFont(f);
        text7.setEditable(false);//设置不可编辑
        text7.setText("提交后可见");
        text7.setForeground(Color.gray);
        text7.setBounds(Width/2-400, 10*Heigth/20-20, 105, 25);
        panel.add(text7);


        
        button[0] = new MyButton(buttonBg2,Width/2-500, 14*Heigth/20-20, 200, 50,"提交答案");
        //添加监听器
        button[0].addActionListener((ActionEvent e)->{
        	String str2 = "确认提交了吗，不再检查检查吗?";
        	if(board.haveEmpty()) {
        		str2 = "还有未做的题目呢，确认提交了吗?";
        	}


			thread.stop();
			thread = new Thread(new Runnable() {
				public void run() {
					while (true) {
						elapsedTime = stopwatch.getElapsedTime();
						// 程序逻辑代码
						stopwatch.start();
						System.out.println(stopwatch.parseTotime(elapsedTime));
					}
				}
			});
			stopwatch.stop();



        	
        	int n = JOptionPane.showConfirmDialog(null,str2,
    				"温馨提示",JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE);
    		//取消选择是-1,确定是0,取消是1
    		if(n==0) {
    			int cnt = board.Judge();
    			text5.setText(String.valueOf(cnt));
    			text6.setText(String.valueOf(board.getExercisesCount()-cnt));
				textTimer.setText(stopwatch.parseTotime(elapsedTime));
    			if(board.getExercisesCount()!=0)
    				text7.setText(String.valueOf(100.0*cnt/board.getExercisesCount())+"%");
    			else text7.setText("100%");
    			text5.setForeground(Color.black);
    			text6.setForeground(Color.black);
    			text7.setForeground(Color.black);
				textTimer.setForeground(Color.red);
    			button[0].setEnabled(false);
    			button[1].setEnabled(true);//可以回退了
				stopwatch.stop();

    			//同时保存本次做题记录
    			Practice p = new Practice();
    			ArrayList<String> res = board.getResult();
    			File resultsfile = new File(PracticesDir,"results_"+practicefile.getName());
    			p.WriteCSVPractice(res, resultsfile);
    			moveFile(practicefile,PracticesDir,true);
    			if(practicefile!=null&&resultsfile!=null) {
    				File file = new File(PracticesCheckings,"checking_"+filename);
    				practicefile = new File(PracticesDir,filename);
    				resultsfile = new File(PracticesDir,resultsfile.getName());
    				Judge.Judege(resultsfile, practicefile, file);
    				moveFile(practicefile,PracticesCorrected,false);
    				moveFile(resultsfile,PracticesCorrected,false);
    			}
    			new Evaluate(recordFile);
    			Evaluate.writeScore(100.0*cnt/board.getExercisesCount());//把分数写到记录文档
    		}
        });
        panel.add(button[0]);
	}
}
//背景(运用继承)
class BackgroundPanel extends JPanel {  
	private static final long serialVersionUID = 1L;
	private Image image = null; 
	public BackgroundPanel(Image image) {  
		this.image = image;  
	} 
	// 固定背景图片，允许这个JPanel可以在图片上添加其他组件  
	protected void paintComponent(Graphics g) {
		//提高画质的一种方法
		Graphics2D graphics = (Graphics2D)g;
		//开启抗锯齿
		RenderingHints renderingHints = new RenderingHints(
				RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		//使用质量压缩
		renderingHints.put(RenderingHints.KEY_RENDERING, 
					RenderingHints.VALUE_RENDER_QUALITY);
		graphics.setRenderingHints(renderingHints);
  	//画背景图片
		graphics.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);  
	}
}
//按钮类
class MyButton extends JButton{
	private static final long serialVersionUID = 1L;
	static final Font f = new Font("华文琥珀",Font.PLAIN,20);
	String buttonBg;
	JLabel jl = null;
	//构造函数，指定按钮的贴图，位置大小，文本
	public MyButton(String buttonBg,int x,int y,int Width,int Heigth,String Text) {
		this.buttonBg = buttonBg;
		this.setLayout(null);
		setBounds(x, y, Width, Heigth);
		jl = new JLabel(Text);
		jl.setFont(f);//设置字体
		jl.setHorizontalAlignment(SwingConstants.CENTER);//设置字体居中
		jl.setForeground(Color.blue);//设置字体颜色为蓝色
		jl.setBounds(0, 0,getWidth() , getHeight());
		add(jl);
		setContentAreaFilled(false);//使按钮没有图片的地方透明
//		this.setBorder(null);
	}
	protected void paintComponent(Graphics g) {
        g.drawImage(new ImageIcon(getClass().getResource(buttonBg)).getImage(),
        		0, 0, this.getWidth(), this.getHeight(), this);  
    }
	//重写JButton中的setEnabled
	public void setEnabled(boolean b) {
		super.setEnabled(b);
		if(b) {
			jl.setForeground(Color.blue);//设置字体颜色为蓝色
		}else {
			jl.setForeground(Color.gray);
		}
	}
}
//黑板类，提供画习题，获取用户答案的方法。
class BoardPanel extends BackgroundPanel{
	private static final long serialVersionUID = 1L;
	
	private Font f = new Font("黑体",Font.BOLD,20);//常用字体类型
	private int ExercisesCount = 0;
	private int sx = 40;
	private int sy = 75;
	private int Width = 80;//整个算式的宽
	private int Width2 = 35;//结果框的宽
	private int Heigth = 25;//整个算式的高
	private int DX = 160;//算式之间的距离
	private int DY = 50;//算式之间的距离
	private int endl = 4;//每行算式个数
//	private int MaxPageCount = 32;//每一页的最大数量
	private ArrayList<String> result = new ArrayList<String>();
	private JTextArea[] resTexts;//存结果的文本
	private JLabel[] ansLabels;//存答案的标签
	private JLabel[] ExeLabels;//存习题的标签
	//重写构造函数
	public BoardPanel(Image image) {
		super(image);
	}
	public void setExercise(Exercise exercise) {
		ExercisesCount = exercise.size();
		ExeLabels = new JLabel[ExercisesCount];
		ansLabels = new JLabel[ExercisesCount];
		resTexts = new JTextArea[ExercisesCount];
		for(int i=0;i<ExercisesCount;++i) {
			ExeLabels[i] = new JLabel();
			ExeLabels[i].setText(exercise.get(i).asString());
			ExeLabels[i].setFont(f);//设置字体格式
			ExeLabels[i].setForeground(Color.white);//设置字体颜色为白色
			ExeLabels[i].setHorizontalAlignment(JLabel.RIGHT);//设置算式向右靠
			ansLabels[i] = new JLabel();
			ansLabels[i].setText(String.valueOf(exercise.get(i).getResult()));
			ansLabels[i].setForeground(Color.green);//设置字体颜色为绿色
			ansLabels[i].setFont(f);//设置字体格式
			ExeLabels[i].setFont(f);//设置字体格式
			ExeLabels[i].setForeground(Color.white);//设置字体颜色为白色
			resTexts[i] = new JTextArea();
			resTexts[i].setFont(f);//设置字体格式
			resTexts[i].setForeground(Color.white);//设置字体颜色为白色
			resTexts[i].setOpaque(false);//设置背景不可见
			//设置边框
			resTexts[i].setBorder(
					BorderFactory.createLineBorder(Color.white, 1));
			//设置光标颜色
			resTexts[i].setCaretColor(Color.white);
		}
	}
	public ArrayList<String> getResult() {
		result.clear();
		for(int i=0;i<ExercisesCount;++i) {
			result.add(resTexts[i].getText());
		}
		return result;
	}
	public void DrawExercise(){
		int x = sx,y = sy;
		this.removeAll();//清空
		this.repaint();//重新绘制
		for(int i=0;i<ExercisesCount;++i) {
			this.add(ExeLabels[i]);
			ExeLabels[i].setBounds(x,y,Width,Heigth);
			if((i+1)%endl==0) {
				x = sx;
				y = y + DY;
			}else {
				x = x+DX;
			}
		}
		//有下面两句才可以使滑动窗口有用
		this.setPreferredSize(new Dimension(720,(ExercisesCount+endl-1)/endl*DY+2*DY));
		this.updateUI();
//		this.revalidate();//重绘可能要用的函数
	}
	public void DrawResultText() {
		int x = sx,y = sy;
		this.repaint();//重新绘制
		for(int i=0;i<ExercisesCount;++i) {
			this.add(resTexts[i]);
			resTexts[i].setBounds(x+Width,y,Width2,Heigth);
			resTexts[i].setEditable(false);//设置不可编辑
			if((i+1)%endl==0) {
				x = sx;
				y = y + DY;
			}else {
				x = x+DX;
			}
		}
		//有下面两句才可以使滑动窗口有用
		this.setPreferredSize(new Dimension(720,(ExercisesCount+endl-1)/endl*DY+3*DY));
		this.updateUI();
//		this.revalidate();//重绘可能要用的函数
	}
	//设置可以编辑
	public void setResEditable() {
		for(int i=0;i<ExercisesCount;++i) {
			resTexts[i].setEditable(true);//设置不可编辑
		}
	}
	//判断函数返回正确题数
	public int Judge(){
		int x = sx,y = sy;
		int cnt=0;
		this.repaint();//重新绘制
		for(int i=0;i<ExercisesCount;++i) {
			this.add(ansLabels[i]);
			ansLabels[i].setBounds(x+Width+Width2+1,y,Width2,Heigth);
			resTexts[i].setEditable(false);//结果框不可再编辑
			if(ansLabels[i].getText().equals(resTexts[i].getText().trim())) {
				//结果正确的情况设置结果框为绿色
//				resTexts[i].setBorder(BorderFactory.createLineBorder(Color.green, 1));
				cnt++;
			}else {
				//否则结果框为红色，答案为红色
//				resTexts[i].setBorder(BorderFactory.createLineBorder(Color.red, 1));
				ansLabels[i].setForeground(Color.red);
			}
			if((i+1)%endl==0) {
				x = sx;
				y = y + DY;
			}else {
				x = x+DX;
			}
		}
		//有下面两句才可以使滑动窗口有用
		this.setPreferredSize(new Dimension(720,(ExercisesCount+endl-1)/endl*DY+3*DY));
		this.updateUI();
//		this.revalidate();//重绘可能要用的函数
		return cnt;
	}
	//判断是否还有未做的习题
	public boolean haveEmpty() {
		for(int i=0;i<ExercisesCount;++i) {
			if(resTexts[i].getText().length()==0)return true;
		}
		return false;
	}
	public int getExercisesCount() {
		return ExercisesCount;
	}
}
//数据报告类，用折线图的形式展示最近做题情况
class DataPanel extends JPanel{
	private static final long serialVersionUID = 1L;
	private ArrayList<Date> X; 
	private ArrayList<Double> Y;
	private int DX = 60;
	private int DY = 60;
	private int SX = 120;
	private int SY = 450;
	private int cnt = 8;
	private Font f = new Font("黑体",Font.BOLD,20);//常用字体类型
	private Font f2 = new Font("黑体",Font.BOLD,15);
	
	Image image = null;
	//构造函数，参数是背景图片，习题文件
	public DataPanel(Image image,File file) {
		this.setLayout(null);
		this.image = image;
		new Evaluate(file);
		X = Evaluate.getDate();
		Y = Evaluate.getScore();
		if(X.size()>cnt)cnt = X.size();
		JLabel label1 = new JLabel("分析:"+Evaluate.analyze());
		label1.setFont(f);
		label1.setForeground(Color.yellow);//设置字体颜色为白色
		label1.setBounds(SX-DX, SY-DY*6-20, 600, 25);
		this.add(label1);
		JLabel labels[] = new JLabel[6];
		for(int i=0;i<=5;++i) {
			labels[i] = new JLabel(String.valueOf(i*20));
			labels[i].setBounds(SX-50,SY-DY*i-10,40,25);
			labels[i].setHorizontalAlignment(JLabel.RIGHT);
			labels[i].setFont(f);
			labels[i].setForeground(Color.white);//设置字体颜色为白色
			this.add(labels[i]);
		}
		JLabel label2 = new JLabel("(正确率%)");
		label2.setBounds(SX-80,SY-DY*5-40,90,20);
		label2.setHorizontalAlignment(JLabel.RIGHT);
		label2.setFont(f2);
		label2.setForeground(Color.white);//设置字体颜色为白色
		this.add(label2);
		JLabel label3 = new JLabel("(时间)");
		label3.setBounds(SX+cnt*DX,SY-7,55,20);
		label3.setHorizontalAlignment(JLabel.RIGHT);
		label3.setFont(f2);
		label3.setForeground(Color.white);//设置字体颜色为白色
		this.add(label3);
		for(int i=0;i<X.size();++i) {
			String str = "<html><body>"+X.get(i).getMonth()+"月"
					+X.get(i).getDate()+"日"+String.format("%02d",X.get(i).getHours())
					+":"+String.format("%02d", X.get(i).getMinutes())
					+"<body></html>";
			JLabel label = new JLabel(str);
			label.setFont(f2);
			label.setForeground(Color.white);
			label.setBounds(SX+(i+1)*DX-25,SY+5, 50, 60);
			label.setHorizontalAlignment(JLabel.CENTER);
			this.add(label);
		}
	}
	protected void paintComponent(Graphics g) {
		//提高画质的一种方法
		Graphics2D graphics = (Graphics2D)g;
		//开启抗锯齿
		RenderingHints renderingHints = new RenderingHints(
				RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		//使用质量压缩
		renderingHints.put(RenderingHints.KEY_RENDERING, 
					RenderingHints.VALUE_RENDER_QUALITY);
		graphics.setRenderingHints(renderingHints);
		//画背景图片
		graphics.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
		//画数据
		graphics.setColor(Color.white);
		graphics.setStroke(new BasicStroke(1.5f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_ROUND,
				3.5f,new float[] {5,5},0f));//画虚线
		for(int i=1;i<=5;++i) {
			graphics.drawLine(SX,SY-DY*i,SX+cnt*DX+7,SY-DY*i);
		}
		graphics.setStroke(new BasicStroke(2f));//改变画笔的粗细
		graphics.drawLine(SX,SY,SX+cnt*DX+7,SY);
		for(int i=1;i<=cnt;++i) {
			graphics.fillOval(SX+i*DX-3,SY-3, 6, 6);
		}
		graphics.setColor(Color.red);
		for(int i=0;i<Y.size();++i) {
			graphics.fillOval(SX+(i+1)*DX-3,(int) (SY-3-Y.get(i)*3), 6, 6);
			if(i>0) {
				graphics.drawLine(SX+(i+1)*DX,(int) (SY-Y.get(i)*3)
						,SX+i*DX,(int) (SY-Y.get(i-1)*3));
			}
		}
	}
	//刷新函数
	public void flush() {
		this.repaint();//重新绘制
		//有下面两句才可以使滑动窗口有用
		this.setPreferredSize(new Dimension(SX*2+cnt*DX,500));
		this.updateUI();
	}
}
